package com.dineroquegastar.urule.utils;

import org.springframework.stereotype.Service;

import java.security.MessageDigest;

@Service
public class Sha1Utils {

    /**
     * 自定义进制(0,1没有加入,容易与o,l混淆)，数组顺序可进行调整增加反推难度，共16个字符。
     */
    private static final char[] BASE = new char[]{'z', '7', 'f', '8', 'v', '4', 'e', '6', 'k', '9', 'm', '2', 'n', '5', 's', '3'};

    /**
     * 为自己带盐，233。
     */
    private static final String salt = "wsbr";


    public String Sha1(String data) {
        //加盐
        data = data + salt;
        byte[] b = data.getBytes();
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(b);
            byte[] b2 = md.digest();
            int len = b2.length;
            char[] chs = new char[len * 2];
            //循环20次
            for (int i = 0, k = 0; i < len; i++) {
                byte b3 = b2[i];//获取摘要计算后的字节数组中的每个字节
                // >>>:无符号右移
                // &:按位与
                //0xf:0-15的数字
                chs[k++] = BASE[b3 >>> 4 & 0xf];
                chs[k++] = BASE[b3 & 0xf];
            }
            result = new String(chs);
        } catch (Exception e) {
            result = null;
        }

        return result;
    }
}